#!/usr/bin/env python
# -*- coding: utf-8 -*-

# import pprint as pp
# import yaml
import codecs
import json
import subprocess, os
import config

config_path = str(os.path.split(os.path.realpath(config.__file__))[0])


def change_encoding(input_dict, encoding='utf-8'):
    if isinstance(input_dict, dict):
        return {change_encoding(key): change_encoding(value) for key, value in input_dict.iteritems()}
    elif isinstance(input_dict, list):
        return [change_encoding(element) for element in input_dict]
    elif isinstance(input_dict, unicode):
        return input_dict.encode(encoding)
    else:
        return input_dict


def get_env_config(env_config_path=None):
    if not env_config_path:
        env_config_path = config_path
    data = dict()
    with codecs.open(os.path.join(env_config_path, 'dcc_launch_env.json'), 'r') as f:
        data = json.load(f)
    data = change_encoding(data)
    if data:
        return data
    else:
        raise RuntimeError("Reading env_config failed!")


def get_os_env():
    return os.environ.copy()  # - ENV_NAME:ENV_VALUE


class LaunchDCC:
    def __init__(self, dcc):
        self._dcc = str(dcc)
        self._env_config = get_env_config(config_path)
        self._os_env = get_os_env()

    def edit_env(self):
        _env = self._os_env
        dcc_name = self._env_config[self._dcc]['Exec']
        all_env = self._env_config[self._dcc]['Env']
        if not all_env:
            return dcc_name, _env
        for e in all_env:
            if e['mode'] == 'over':
                _env[e['name']] = e['value']
            elif e['mode'] == 'pre':
                _env[e['name']] = e['value'] + ";" + os.environ.get(e['name'], '')
            elif e['mode'] == 'post':
                _env[e['name']] = os.environ.get(e['name'], '') + ";" + e['value']
            else:
                pass
        # print dcc_name, _env
        return dcc_name, _env

    def launch_dcc(self):
        dcc, _env = self.edit_env()
        subprocess.Popen(dcc, env=_env)






